﻿using Brilliant_see.Core.AbstractClass;
using Brilliant_see.Core.Interfaces;
using Brilliant_see.Core.structs;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;

namespace Brilliant_see.MapSources.Comics
{
    public class BaoziComic : Comic
    {
        private bool _isReverseList = true;
        private string? _html;
        private string? _blurb;
        private Chapter[]? _chapters;

        public override bool IsReverseList
        {
            get { return _isReverseList; }
            set
            {
                if (_isReverseList != value)
                {
                    _isReverseList = value;
                    if (_chapters is not null)
                        Chapters = _chapters.Reverse().ToArray();
                }
            }
        }

        public override int ReadChapterIndex { get; set; }

        public override string Name { get; set; }
        public override string Witer { get; set; }
        public override IMapSource ComicSource { get; init; }
        public override string ComicUrl { get; set; }
        public override string Cover { get; set; }
        public override string LateInfo { get; set; } = string.Empty;

        public override string? Blurb
        {
            get { return _blurb; }
            set { _blurb = value; OnPropertyChanged(); }
        }

        public override Chapter[]? Chapters
        {
            get { return _chapters; }
            set { _chapters = value; OnPropertyChanged(); }
        }

        public BaoziComic(IMapSource source, string url, string name, string cover, string witer)
        {
            ComicSource = source;
            ComicUrl = url;
            Name = name;
            Cover = cover;
            Witer = witer;
        }

        public override async Task LoadDelayDataAsync()
        {
            await UpdateChaptersAsync();

            if (!string.IsNullOrEmpty(_html))
                Blurb = Regex.Match(_html, "<p class=\"comics-detail__desc overflow-hidden\".*?>(.*?)</p>").Groups[1].Value;
        }

        public override async Task UpdateChaptersAsync()
        {
            _html = await ComicSource.HttpClient.GetStringAsync(ComicUrl);

            var chaptersHtml = _html.Substring(_html.IndexOf(">章节目录</div>")).Replace("&amp;", "&");
            var matches = Regex.Matches(chaptersHtml, "comics-chapters\".+?><a href=\"(.+?)\".*?class=\"comics-chapters__item.+?<span.*?>(.*?)</span>");

            var count = matches.Count;
            var chapters = new Chapter[count];
            for (int i = 0; i < count; i++)
            {
                var match = matches[i];
                chapters[i] = new Chapter(match.Groups[2].Value, match.Groups[1].Value);
            }

            Chapters = _isReverseList ? chapters.Reverse().ToArray() : chapters;
        }

        public override Task ReverseChaptersAsync()
            => Task.Run(() => { IsReverseList = !IsReverseList; });
    }
}